<?php
namespace app\controller;

use app\BaseController;
use app\model\Article;
use app\model\ArticleCol;
use app\model\ArticleLab;
use app\model\User;
use app\model\UserInfoHobby;
use app\model\UserInfos;
use think\facade\View; // 使用模板引擎
use think\facade\Db; // 使用Db数据
use think\Request; // 系统的think\Request对象
use think\facade\Session;
use think\facade\FileSystem;
class Index extends BaseController
{


    // index 渲染
    public function index(Request $request){
        // 判断一下session中是否存在值
        $flag =Session::get('uname');
        //dump(Session::all());
        if(!isset($flag)){
            // 先修改视图模板
            view::engine()->layout(false);
            view::engine()->layout('logreglayout');
            return view::fetch("login/login");
        }else{
            // 从数据库中查询出文章信息，并且渲染
            $colList = [
                "springboot" => "",
                "ssm" => "",
                "Linux" =>  "",
                "MySql" => "",
                "ThinkPHP" => "",
                "Redis" => ""
            ];
            $labelList = [
                "java"=>"",
                "python"=>"",
                "php"=>"",
                "C"=>"",
                "Go"=>"",
                "Hadoop"=>"",
            ];
            // 设定每页5条
            $page = $request->param("page")==null ? 0 :$request->param("page")*5;
            $size = $page==0 ? 5:$page+5;
            // 每次查询  0,5 5,10

            $article = new Article();
            $rs =$article->queryArticleAllByUser(Session::get("id"),$page,$size); // 文章信息
            $rs2=$article->countAt(Session::get("id"));  // 总数
            // total 总页数
            $total = ceil($rs2/$size);


            // 向前端发送数据
            view::assign("colList",$colList); //分栏下拉
            view::assign("labelList",$labelList); //文章类型下拉
            view::assign("atList",$rs); //文章类型下拉
            view::assign("count",$rs2); //总数
            view::assign("page",$page); //页数
            view::assign("total",$total); //页数
            view::assign("uname",Session::get('uname'));
            return view::fetch();
        }

     }

     // 登录检查
    public function loginCheck(Request $request){
        $uname = $request->param('uname');
        $upwd = $request->param('upwd');
        $yzm = $request->param('yzm');

        // 校验验证码,错误直接返回
        if(!captcha_check($yzm)){
            return "4";
        }
        // dump($request->param());
        $model = new User();
        $rs = $model->checkUser($uname);
        if($rs==null){
            // 不存在该用户
            return "2";
        }else{
            $rs2 = $model->checkUserPwd($uname,$upwd);
            if($rs2==null){
                // 密码错误
                return "3";
            }else{
                // 登录成功，设定session ,开启session
                Session::set('uname', $uname);
                Session::set('id', $rs2->id);
                return "1";
            }
        }

    }

    // 注册检查
    public function registerCheck(Request $request){
        $uname = $request->param("uname");
        $upwd = $request->param("upwd");
        $model = new User();
        // 判断账号是否已经存在，即用户名不能重复
        $check = $model->checkUser($uname);
//        var_dump($request->param());
//         var_dump(is_null($check)); //为true 说明该用户名已经存在
        if($check==null){
            // 返回自增主键
            $id = $model->insertUser($uname,$upwd);
            // 在userinfo 和  liketag也进行插入

            // 用户信息表插入
            $uinfo= new UserInfos();
            $uid = $uname.$id;
            // dump($uid);
            // 爱好表插入
            $hb = new UserInfoHobby();
            $uinfo->insertUserInfo($id,$uname,$uid);
            $hb->insertHb($uid);
            return "1";
        }else{
            return "-1";
        }
    }

    // 记录一下，view::engine()中存放了view视图的配置

    // 单篇文章浏览
    public function lookAt(Request $request){
        $id = $request->param("id");
        $uid = Session::get("id");
        $art = new Article();
        $data = $art->queryArticleById($id,$uid);
        view::assign("data",$data);
        view::assign("uname",Session::get('uname'));
        return view::fetch();
    }

    public function lookAtT(Request $request){
        $id = $request->param("id");
        $uid = Session::get("id");
        $art = new Article();
        $data = $art->queryArticleById($id,$uid);
        view::assign("data",$data);
        view::assign("uname",Session::get('uname'));
        view::engine()->layout(false);
        view::engine()->layout('userlayout');
        return view::fetch();
    }

    // 多条件查询
    public function search(Request $request){
        $data = $request->param();
        //dump($data);
        $year = isset($data["year"]) ? $data["year"] :"";
        $month = isset($data["month"]) ? $data["month"] :"";
        $time = $year."-0".$month;
        $label = isset($data["label"]) ?  $data["label"] : "";
        $col = isset($data["col"]) ?  $data["col"] : "";
        $title = isset($data["title"]) ? $data["title"] : "";
       // var_dump($data);
        $colList = [
            "springboot" => "",
            "ssm" => "",
            "Linux" =>  "",
            "MySql" => "",
            "ThinkPHP" => "",
            "Redis" => ""
        ];
        $labelList = [
            "java"=>"",
            "python"=>"",
            "php"=>"",
            "C"=>"",
            "Go"=>"",
            "Hadoop"=>"",
        ];

        // 设定每页5条
        $page = $request->param("page")==null ? 0 :$request->param("page")*5;
        $size = $page==0 ? 5:$page+5;
        // 每次查询  0,5 5,10

        $article = new Article();
        $rs =  $article->queryLike($time,$label,$col,$title,$page,$size,Session::get("id"));
        $rs2=$article->countAtLike(Session::get("id"),$label,$col,$title,$page,$size,Session::get("id"));  // 总数
        // total 总页数
        $total = ceil($rs2/$size);

        // 向前端发送数据
        view::assign("colList",$colList); //分栏下拉
        view::assign("labelList",$labelList); //文章类型下拉
        view::assign("atList",$rs); //文章类型下拉
        view::assign("count",$rs2); //总数
        view::assign("page",$page); //页数
        view::assign("total",$total); //页数
        view::assign("uname",Session::get('uname'));
        return view::fetch();
    }
    // 文章更新
    public function updAt(Request $request){
        $data = $request->param();
        $data['lastUpdTime']=date("Y-m-d H:i:s");
        $data['content']=nl2br($data['content']); // 将回车换行进行转换
        $data['labList']=implode(',',$data["label"]);
        $data['colList']=implode(',',$data["arr"]);
        foreach ($data as $k=>$v){
            if($k=="arr"){
                continue;
            }
            if($k=="label"){
                continue;
            }
            if($k=="uid"){
                continue;
            }
            if($k=="id"){
                continue;
            }
            // 对数据库文章的普通字段进行插入 user_article
            $atData["$k"]=["$v"];
        }



        //dump($atData);
       // dump($data);

        $labelList = [
            "java"=>"",
            "python"=>"",
            "php"=>"",
            "C"=>"",
            "Go"=>"",
            "Hadoop"=>"",
        ];

        $colList = [
            "springboot" => "",
            "ssm" => "",
            "Linux" =>  "",
            "MySql" => "",
            "ThinkPHP" => "",
            "Redis" => ""
        ];


        $article = new Article();
        $article->saveArticle($atData,$data["uid"],$data["id"]);

        $label =$data["label"];
        //dump($label);

        $arr = $data["arr"];
        //dump($arr);

        foreach ($arr as $v){
            $colList["$v"]=$v;
        }

        foreach ($label as $v){
            $labelList["$v"]=$v;
        }

        $labAdd = new ArticleLab();
        $labAdd->saveArticleLab($labelList,$data["uid"],$data["id"]);

        $colAdd = new ArticleCol();
        $colAdd->saveArticleCol($colList,$data["uid"],$data["id"]);

        // 视图跳转传递参数 重定向
        return redirect('http://localhost:8000/index.php/index/index');
    }

    public function login(){
       return view::fetch();
    }

    // 个人信息页面渲染
    public function userInfo(){

        // 切换模板，需要将当前的模板视图false掉
        view::engine()->layout(false);
        view::engine()->layout('userlayout');
        // 获取 session 值
        $id = Session::get("id");
        $uname =  Session::get("uname");
        $uid = $uname.$id;
        // 从数据库查询出用户的基本信息和身份信息和爱好信息
        $userinfo =new UserInfos();
        $uinfos = $userinfo->queryUserInfo($id);
        // 设置hobby
        $infoHobby = new UserInfoHobby();
        $hobby = $infoHobby->queryHobby($uid);
//        dump($uinfos);


        // 将数据发送到视图上
        $hblist = [
            "Java"=>false,
            "Python"=>false,
            "PHP"=>false,
            "HTML"=>false,
            "CSS"=>false,
            "JS"=>false,
            "C"=>false,
            "Golang"=>false,
            "Ruby"=>false,
            "Rust"=>false
        ];



        unset($hobby[0]["id"]);// 将id去掉
//        dump($hobby[0]);
        foreach ($hobby[0] as $v){
           $hblist["$v"]=true;
        }

        // 移除两个空字符串关联数组
        unset($hblist[""]);
        unset($hblist[" "]);

//        dump($hblist);

        view::assign([
            "uname"=>$uinfos["uname"],
            "id"=>$uinfos["id"],
            "sex"=>$uinfos["sex"],
            "address"=>$uinfos["address"],
            "uid"=>$uid,
            "birthday"=>$uinfos["birthday"],
            "scname"=>$uinfos["scname"],
            "major"=>$uinfos["major"],
            "intake"=>$uinfos["intake"],
            "education"=>$uinfos["education"],
            "corname"=>$uinfos["corname"],
            "jobname"=>$uinfos["jobname"],
            "profession"=>$uinfos["profession"],
            "identity"=>$uinfos["identity"],
            "xueli"=>["初中","高中","大学","硕士研究生","博士研究生"],
            "hblist"=>$hblist,
            "sflist"=>["在校生","毕业生","在职程序员","社会人员"],
            "hobby"=>$hobby
        ]);


        return view::fetch();

    }


    public function home(Request $request){
        $page = $request->param("page")==null ? 0 :$request->param("page")*5;
        $size = $page==0 ? 5:$page+5;
        // 每次查询  0,5 5,10

        $article = new Article();
        $rs =$article->queryArticleAllByUser(Session::get("id"),$page,$size); // 文章信息
        $rs2=$article->countAt(Session::get("id"));  // 总数
        // total 总页数
        $total = ceil($rs2/$size);


        // 向前端发送数据
        view::assign("atList",$rs); //文章类型下拉
        view::assign("count",$rs2); //总数
        view::assign("page",$page); //页数
        view::assign("total",$total); //页数
        view::assign("uname",Session::get('uname'));
        view::engine()->layout(false);
        view::engine()->layout('userlayout');
        return view::fetch();
    }

    public function addAt(){
        view::engine()->layout(false);
        view::engine()->layout('userlayout');
        return view::fetch();
    }


    public function delAt(Request $request){
        $id = $request->param("id");
        $at = new Article();
        $at->delAtById($id);

        $col = new ArticleCol();
        $col->delAtById($id);

        $lab =  new ArticleLab();
        $lab->delAtById($id);

        return redirect('http://localhost:8000/index.php/index/index');
    }
    // 文章保存
    public function addAtToSave(Request $request){
        $data = $request->param();
        // 获取图片
        $file = $request->file('image');
        // 上传到本地服务器
        $savename = Filesystem::disk('photo') -> putFile('photo', $file, 'md5');;
        //dump($savename);
        // 将图片路径保存
        $data['image']=$savename;
        $data['addTime']=date("Y-m-d H:i:s");
        $data['lastUpdTime']=null;
        $data['content']=nl2br($data['content']); // 将回车换行进行转换
        $data['uid']=Session::get("id");
        $data['id']=$data["uid"].$data["title"];
        $data['labList']=implode(',',$data["label"]);
        $data['colList']=implode(',',$data["arr"]);
       // print_r( $data);

        $atData = [];
        // 将数组进行处理
        foreach ($data as $k=>$v){
            if($k=="arr"){
                continue;
            }
            if($k=="label"){
                continue;
            }
            // 对数据库文章的普通字段进行插入 user_article
            $atData["$k"]=["$v"];
        }

        // dump($atData);

        // 文章普通信息插入
        $article = new Article();
        $article->insertArticle($data);

        // 获取专栏分类的数据 user_articlecol
        $col = $data["arr"];
        //dump($col);
        $colList = [
            "springboot" => "",
            "ssm" => "",
            "Linux" =>  "",
            "MySql" => "",
            "ThinkPHP" => "",
            "Redis" => ""
        ];

        foreach ($col as $key1=>$value1){
            $colList["$value1"]=$value1;
        }
        //dump($colList);

        // 插入数据
        $colAdd = new ArticleCol();
        $colAdd->insertArticleCol($colList,$data["uid"],$data["id"]);

        // 获取标签栏的 user_articlelab
        $label = $data["label"];


        $labelList = [
            "java"=>"",
            "python"=>"",
            "php"=>"",
            "C"=>"",
            "Go"=>"",
            "Hadoop"=>"",
        ];

        foreach ($label as $key2=>$value2){
            $labelList["$value2"]=$value2;
        }
        //dump($labelList);
        $labAdd = new ArticleLab();
        $labAdd->insertArticleLab($labelList,$data["uid"],$data["id"]);

        // 跳转到查看文章页面
        return redirect('http://localhost:8000/index.php/index/index');
    }


    // 编辑
    public function editAt(Request $request){
       $id =  $request->param("id");

       $uid = Session::get("id");
       $art = new Article();
       $data = $art->queryArticleById($id,$uid);


        $data["colList"] = explode(',', $data["colList"] );
        $data["labList"] = explode(',',$data["labList"] );

        $lab1 =  new ArticleLab();
        $rs1 =  $lab1->queryArtLab($id,$uid)->toArray();

        foreach ($rs1 as $k=>$v){
            if($k=="uid"){
                continue;
            }
            if($k=="atId"){
                continue;
            }
            $lab2["$k"]=$v;
        }

       // dump($lab2);


        $col1 = new ArticleCol();
        $rs2 = $col1->queryArtCol($id,$uid)->toArray();


        foreach ($rs2 as $k=>$v){
            if($k=="userId"){
                continue;
            }
            if($k=="atId"){
                continue;
            }
            $col2["$k"]=$v;
        }
        //dump($col2);



        $data["colList"] = $col2;
        $data["labList"] = $lab2;

        //dump($data["colList"]);
       // print_r($data["colList"]);
//        dump($labelList);
        view::assign("data",$data);
        view::assign("lab2",$lab2);
        view::assign("col2",$col2);

        return view::fetch("upd_at");
    }


    // 清除session
    public  function  clear(){
        Session::clear();
        return redirect('http://localhost:8000/index.php/index/index');
    }


}
